package com.lut.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @user:dell
 * @date:2020年09月23 19:22
 */
public class JdbcUtils {
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> conns=new ThreadLocal<Connection>();
    static {

        try {
            Properties properties=new Properties();
//        读取jdbc.properties属性配置文件
            InputStream inputStream =JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(inputStream);
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
            System.out.println(dataSource.getConnection());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        Connection connection=conns.get();
        if(connection==null){
            try {
                connection=dataSource.getConnection();
                connection.setAutoCommit(false);
                conns.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return  connection;
    }
    public static void commitAndClose(){
        Connection connection=conns.get();
        if(connection!=null){
            try {
                connection.commit();

            } catch (SQLException e) {
               e.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        conns.remove();
    }
    public static void rollBackAndClose(){
        Connection connection=conns.get();
        if(connection!=null){
            try {
                connection.rollback();

            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        conns.remove();

    }
//    public static void close(Connection conn){
//        if(conn!=null){
//            try {
//                conn.close();
//            } catch (SQLException throwables) {
//                throwables.printStackTrace();
//            }
//        }
//    }

}
